package com.gci.lib_markdown_editor.viewer

import android.webkit.WebResourceResponse
import androidx.webkit.WebViewAssetLoader
import java.io.File


import android.util.Log

class MyFilePathHandler(private val root: File) : WebViewAssetLoader.PathHandler {

    companion object {
        private const val TAG = "MyFilePathHandler"
    }

    override fun handle(path: String): WebResourceResponse? {
        val file = File(root, path.trimStart('/'))
        Log.d(TAG, "请求资源路径：$path")
        Log.d(TAG, "映射文件路径：${file.absolutePath}")

        return if (file.exists()) {
            Log.d(TAG, "资源存在，准备返回：${file.name}")
            val mimeType = when {
                path.endsWith(".jpg", ignoreCase = true) || path.endsWith(".jpeg", ignoreCase = true) -> "image/jpeg"
                path.endsWith(".png", ignoreCase = true) -> "image/png"
                path.endsWith(".gif", ignoreCase = true) -> "image/gif"
                path.endsWith(".html", ignoreCase = true) -> "text/html"
                path.endsWith(".css", ignoreCase = true) -> "text/css"
                path.endsWith(".js", ignoreCase = true) -> "application/javascript"
                path.endsWith(".mp4", ignoreCase = true) -> "video/mp4"
                else -> "application/octet-stream"
            }
            WebResourceResponse(mimeType, "UTF-8", file.inputStream())
        } else {
            Log.e(TAG, "资源不存在：${file.absolutePath}")
            // 返回404响应，防止WebView继续访问网络
            WebResourceResponse(null, null, null)
        }
    }
}
